import cookieParser from 'cookie-parser';
import dotenv from 'dotenv';
import express from 'express';
import expressip from 'express-ip';
import createError from 'http-errors';
import logger from 'morgan';
import path from 'path';
import mainRouter from './routes/index.js';

import { fileURLToPath } from 'url';
import globalCache from './cache.js';
import CacheBuffer from './middleWare/cache/index.js';


const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
var y = new Date().getFullYear()
var m = new Date().getMonth() + 1


dotenv.config()
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// app.use(formidable());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

//设置跨域访问
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  // nginx 默认不支持_，会丢失头部信息,需要在nginx的http配置 underscores_in_headers on;
  res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,X-CSRF-TOKEN,authorization,token,merchant_id",);
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By",' 3.2.1')
  res.header("Content-Type", "application/json;charset=utf-8");
  res.header("Content-Disposition", "inline");
  next();
});



// function textOurUrl() {
//   const url = 'https://www.google.com'
//   http.get(url,{
//     httpsAgent: new HttpsProxyAgent('http://127.0.0.1:10809')
//   }).then((result) => {
//     
    
//   }).catch(err => {
//     
//   })
// }


// try {
//   textOurUrl()
// } catch (error) {
//   throw Error(error)
// }

// 读取缓存文件
// app.use(CacheBuffer.readCache)
CacheBuffer.readCache()
setInterval(() => {
  CacheBuffer.writeCache()
}, 10 * 1000);

const ignoreList = [
  '/favicon.ico'
]

const whiteList = [
	'/spider',
  '/app/bot',
  '/app/news/list',
  '/weixin/login', // 小程序微信登录
  '/weixin/authorize', //服务器验证
  '/menu/mini/tabbarMenu', // 小程序tabbar
  '/common/cache/data', // 获取缓存
  '/app/schedule/list',
  // '/common/files/list',
  '/common/upload/files',
  '/users/register',
  '/users/login',
  '/common/files/parseExcel',
  '/email/send',
  '/common/dict', // 字典
]

const isValideWhitePath = (path) => {
  
  return whiteList.some(e => {
    return path.indexOf(e) > -1
  })
}

const isIgnorePath = (path) => {
  return ignoreList.some(e => {
    return path.indexOf(e) > -1
  }) 
}

app.use((req,res,next) => {
  if (isIgnorePath(req._parsedUrl.pathname)) {
    res.send()
  } else {
    next()
  }
})

app.use(function(req,res,next) {

  const token = req.headers.authorization || req.headers.token

  const hasLogin = globalCache.hasKey('token',`${token}`)
  
  if (!isValideWhitePath(req._parsedUrl.pathname)) {
    if (!token) {
      next(createError(401))
    } else if (!hasLogin) {
      res.json(req.app.locals.hasexpired('登录已过期'))
      return
    } else {
      next()
    }
  }else {
    next()
  }
})


// main router
app.use('/',mainRouter)

// catch 404 and forward to error handler


// error handler
app.use(function(err, req, res, next) {    
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  if(res.locals.message == 'Unauthorized') {
    res.json(req.app.locals.unlogin(null,'缺少token'))
  } else if (err == 409) {
    res.json(req.app.locals.hasexpired(null,'登录已过期'))
  } else if (res.locals.message == 'Not Found') {
    res.json(req.app.locals.nofound(null,'服务未找到'))
  } else {
    res.json(req.app.locals.error(null,err.message))
  }
});

process.on('uncaughtException', (err) => {  
  console.error('Uncaught Exception:', err);  
  // 这里你可以选择记录错误、发送警报等，但不要直接退出进程。  
});  
  
process.on('unhandledRejection', (reason, promise) => {  
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);  
  // 同样，记录错误并发送警报，但不要直接退出进程。  
});



app.locals.success = (data = {},message = 'success') => {
  return {
    code: 0,
    data,
    message
  }
}

app.locals.unlogin = (data = {},message = 'No Token') => {
  return {
    code: 401,
    data,
    message
  }
}
app.locals.hasexpired = (data = {},message = '已过期，重新登录') => {
  return {
    code: 409,
    data,
    message
  }
}
app.locals.nofound = (data = {},message = '服务未找到') => {
  return {
    code: 404,
    data,
    message
  }
}

app.locals.error = (data = {},message = data) => {
  return {
    code: 500,
    data,
    message
  }
}

export default app
